const express = require('express');
const router = express.Router();
const { Article } = require('../../models');
const { success, failure } = require('../../utils/responses');
const { findListPagination } = require('../../utils/pagination');
const { NotFound } = require('http-errors');

/**
 * 查询文章列表
 * GET /articles
 */
router.get('/', async function (req, res) {
  try {
    const query = req.query;
    const condition = {
      attributes: { exclude: ['content'] },
    };
    const data = await findListPagination(query, (pagination) =>
      Article.findAndCountAll({ ...condition, ...pagination })
    );
    success({
      res,
      message: '查询文章列表成功。',
      data,
    });
  } catch (error) {
    failure({ res, error });
  }
});
/**
 * 查询文章详情
 * GET /articles/:id
 */
router.get('/:id', async function (req, res) {
  try {
    const { id } = req.params;

    const article = await Article.findByPk(id);
    if (!article) {
      throw new NotFound(`ID: ${id}的文章未找到。`);
    }

    success({ res, message: '查询文章成功。', data: { article } });
  } catch (error) {
    failure({ res, error });
  }
});

module.exports = router;
